import time

from channels.generic.websocket import WebsocketConsumer
from channels.generic.websocket import AsyncWebsocketConsumer
import json
import numpy as np
from apps.services import models
from django.core.cache import cache
from asgiref.sync import async_to_sync
import itkf as config
from django.utils.safestring import mark_safe
import os

ENV_PROFILE = os.getenv("ENV")
if ENV_PROFILE == "test":
    import itkf.test_settings as config
elif ENV_PROFILE == "production":
    import itkf.prd_settings as config
else:
    import itkf.settings as config

corpid = config.weChatWork["corpid"]
sourceFile = config.weChatWork["sourceFile"]
serviceUser = config.weChatWork["serviceUser_"]
customeUser = config.weChatWork["customeUser_"]
media_image_url = config.weChatWork["media_image_url"]


# 根据类型选择发送对应的格式
def sendContent(item):
    MsgType = item["MsgType"]
    content = item["content"]
    if MsgType == "image":
        content = mark_safe("img[{0}]".format(content))
    if MsgType == "video":
        content = mark_safe("video[{0}]".format(content))
    if MsgType == "voice":
        content = mark_safe("audio[{0}]".format(content))
    return {'username': item['username'], 'avatar': item['avatar'], 'id': item['id'], 'type': 'friend',
            'content': content}


class ChatConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        print("connect")
        groupName = ""
        self.user = self.scope["user"]
        # 客服上线
        username = self.scope["user"].username
        print("username===========", username)

        agentid = 1

        staff = models.staffService.objects.filter(agent__id=agentid)

        kfUser = models.KF.objects.filter(userid=username).first()
        if kfUser:
            groupName = serviceUser + str(kfUser.agent.id) + username
            kfUser.status = True
            kfUser.save()
        else:
            groupName = customeUser + username

        self.room_group_name = groupName
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()

        await self.receive("once")

    async def disconnect(self, close_code):
        print("disconnect")
        print(close_code)
        print(self.scope["user"])
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )
        # 客服下线
        kfUser = models.KF.objects.filter(userid=self.scope["user"].username).update(status=False)
        print(kfUser)

    async def receive(self, text_data):

        self.user = self.scope["user"]
        # Send message to room group
        # loginKF = models.KF.objects.filter(userid=self.user).first()
        AgentID = "1"
        redisMessage = cache.iter_keys(AgentID + "$*")
        for msgg in redisMessage:
            currentMsg = cache.get(msgg)
            for item in currentMsg:
                message = sendContent(item)
                await self.channel_layer.group_send(
                    self.room_group_name,
                    {
                        'type': 'chat_message',
                        'message': message
                    }
                )
                newRedisMessage = cache.get(msgg)
                if currentMsg == newRedisMessage:
                    cache.delete(msgg)

    async def chat_message(self, message):
        print(message)
        # Send message to WebSocket
        await self.send(text_data=json.dumps(message))